package com.example.test_aidl_systemui

import android.app.Service
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.test_aidl_carservice.IMyAidlInterface
import com.example.test_aidl_carservice.IMyCallBack
import com.example.test_aidl_carservice.ResultHolder


class MainActivity : AppCompatActivity() {
    private var iMyAidlInterface:IMyAidlInterface? = null
    private val serviceConnection:ServiceConnection = object :ServiceConnection{
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) { //绑定成功
            Toast.makeText(this@MainActivity,"打开后备箱",Toast.LENGTH_LONG).show()
            iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service)
        }

        override fun onServiceDisconnected(name: ComponentName?) {//

        }

    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        val intent = Intent()
        intent.setAction("com.bw.car")
        intent.setPackage("com.example.test_aidl_carservice")
        bindService(intent,serviceConnection,Service.BIND_AUTO_CREATE) //绑定服务
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(serviceConnection)
    }

    fun open(view: View) {
        iMyAidlInterface?.openBackDoor()
        Toast.makeText(this,"打开后备箱",Toast.LENGTH_LONG).show()
    }
    fun getSpeed(view: View) {
        val speed =  iMyAidlInterface?.speed
        Toast.makeText(this,"获得车速"+speed,Toast.LENGTH_LONG).show()
    }

    fun getSpeed2(view: View) {
        iMyAidlInterface?.getSpeed2(object:IMyCallBack.Stub(){
            override fun onSuccess(speed: Int) {
                Handler(Looper.getMainLooper()).post {
                    Toast.makeText(this@MainActivity, "异步获得车速" + speed, Toast.LENGTH_LONG).show()
                }


            }

            override fun onError(message: String?) {

            }

        })
    }

    fun add(view: View) {
        val resultHolder = ResultHolder()
        iMyAidlInterface?.add(10,6,resultHolder) //resultHolder：输出参数，服务端修改输入到客户端
        Toast.makeText(this,"结果"+resultHolder.value,Toast.LENGTH_LONG).show()
    }


}